package org.huawei.view;

import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.control.*;
import javafx.scene.control.cell.ComboBoxTableCell;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.image.Image;
import javafx.scene.layout.*;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.util.Callback;
import org.huawei.model.domain.*;
import org.huawei.controller.*;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MainView {

    private VBox centerBox;  // 中心区域
    private PermissionController permissionController;
    private HomeworkController homeworkController;
    private UserController userController;
    private RoleController roleController;
    private SubmissionController submissionController;

    public void start(Stage primaryStage, User user) throws SQLException {
        permissionController = new PermissionController(primaryStage);
        homeworkController = new HomeworkController(primaryStage);
        userController = new UserController(primaryStage);
        roleController = new RoleController(primaryStage);
        submissionController = new SubmissionController(primaryStage);

        // 更新作业数据
        homeworkController.updateHomeworkDataOnLogin();

        primaryStage.setTitle("作业管理系统");

        // 创建菜单栏
        VBox menuBox = new VBox(5);
        menuBox.setPrefWidth(200);
        menuBox.setStyle("-fx-background-color: #FFFFFF;");
        menuBox.setPadding(new Insets(5, 0, 0, 0));
        menuBox.setAlignment(Pos.TOP_CENTER);

        // 创建左侧菜单按钮
        Button submitBtn = new Button("作业提交");
        Button userManagementBtn = new Button("用户管理");
        Button roleManagementBtn = new Button("权限管理");
        Button homeworkManagementBtn = new Button("作业管理");
        Button accountManagementBtn = new Button("账号管理");

        // 设置按钮样式
        setButtonStyle(submitBtn, "#c3bef0");
        setButtonStyle(userManagementBtn, "#cca8e9");
        setButtonStyle(roleManagementBtn, "#c3bef0");
        setButtonStyle(homeworkManagementBtn, "#cadefc");
        setButtonStyle(accountManagementBtn, "#fef0ff");

        List<Permission> permissions =  permissionController.getUserPermissionsByRoleId(user.getRoleId());
        // 根据permission 显示不同的按钮
        for (Permission permission : permissions) {
            int permissionId = permission.getPermissionId();

            switch (permissionId) {
                case 1:
                    if (!menuBox.getChildren().contains(roleManagementBtn)) {
                        menuBox.getChildren().add(roleManagementBtn);
                    }
                    break;
                case 2:
                    if (!menuBox.getChildren().contains(userManagementBtn)) {
                        menuBox.getChildren().add(userManagementBtn);
                    }
                    break;
                case 3:
                case 4:
                case 5:
                case 6:
                    if (!menuBox.getChildren().contains(homeworkManagementBtn)) {
                        menuBox.getChildren().add(homeworkManagementBtn);
                    }
                    break;
                case 7:
                    if (!menuBox.getChildren().contains(submitBtn)) {
                        menuBox.getChildren().add(submitBtn);
                    }
                    break;
                default:
                    break;
            }
        }
        menuBox.getChildren().add(accountManagementBtn);

        // 状态栏，使用 HBox 容器
        HBox statusBar = new HBox();
        statusBar.setPrefHeight(35);
        statusBar.setAlignment(Pos.CENTER_LEFT);
        statusBar.setStyle("-fx-background-color: #a2d5f2;");
        Label statusLabel = new Label("        您好，亲爱的  " + user.getUserName() + " ，欢迎登录 “龙飞” 版作业管理系统，祝您生活愉快！");
        statusLabel.setStyle("-fx-font-size: 18px; -fx-font-family: 'Arial';");
        statusBar.getChildren().add(statusLabel);

        // 中心内容区域布局
        centerBox = new VBox(10);
        centerBox.setAlignment(Pos.TOP_CENTER);

        // 设置背景图片
        Image bgImage = new Image(getClass().getResource("/image/background3.png").toExternalForm());
        BackgroundImage backgroundImage = new BackgroundImage(bgImage,
                BackgroundRepeat.NO_REPEAT,
                BackgroundRepeat.NO_REPEAT,
                BackgroundPosition.CENTER,
                new BackgroundSize(BackgroundSize.AUTO, BackgroundSize.AUTO, false, false, true, true));

        centerBox.setBackground(new Background(backgroundImage));
        centerBox.setStyle("-fx-opacity: 1.0;");

        // BorderPane布局 - 左边菜单，右边内容
        BorderPane borderPane = new BorderPane();
        borderPane.setLeft(menuBox);
        borderPane.setCenter(centerBox);
        borderPane.setTop(statusBar);

        // 设置按钮点击事件
        submitBtn.setOnAction(e -> setCenterContentForSubmission(primaryStage, user));
        userManagementBtn.setOnAction(e -> {
            try {
                setCenterContentForUser(primaryStage, user);
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
        });
        roleManagementBtn.setOnAction(e -> setCenterContentForPermission());
        homeworkManagementBtn.setOnAction(e -> {
            try {
                setCenterContentForHomework(primaryStage, user);
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
        });
        accountManagementBtn.setOnAction(e -> setCenterContentForAccount(primaryStage, user));

        // 创建场景
        Scene scene = new Scene(borderPane, 1150, 660);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void setCenterContentForSubmission(Stage primaryStage, User user) {
        centerBox.getChildren().clear();
        centerBox.setPadding(new Insets(10, 0, 0, 0));

        // 创建表格视图
        TableView<Homework> homeworkTable = new TableView<>();

        // 定义表格列
        TableColumn<Homework, Integer> homeworkIdCol = new TableColumn<>("作业ID");
        homeworkIdCol.setCellValueFactory(new PropertyValueFactory<>("homeworkId"));
        homeworkIdCol.setPrefWidth(80);

        TableColumn<Homework, String> homeworkNameCol = new TableColumn<>("作业名称");
        homeworkNameCol.setCellValueFactory(new PropertyValueFactory<>("homeworkName"));
        homeworkNameCol.setPrefWidth(150);

        TableColumn<Homework, String> descriptionColumn = new TableColumn<>("作业描述");
        descriptionColumn.setPrefWidth(300);

        descriptionColumn.setCellValueFactory(data -> {
            String fullDescription = data.getValue().getHomeworkDescription();
            int maxLength = 30; // 截取的最大字符数
            String shortenedDescription;

            // 如果内容超过 maxLength 个字符，截取并添加省略号
            if (fullDescription.length() > maxLength) {
                shortenedDescription = fullDescription.substring(0, maxLength) + "...";
            } else {
                shortenedDescription = fullDescription;
            }
            return new SimpleStringProperty(shortenedDescription);
        });

        descriptionColumn.setCellFactory(column -> new TableCell<Homework, String>() {
            private final Button viewButton = new Button("查看");

            @Override
            protected void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);
                if (empty || item == null) {
                    setText(null);
                    setGraphic(null);
                } else {
                    setText(item);
                    setGraphic(viewButton);
                    viewButton.setOnAction(event -> {
                        Homework homework = getTableView().getItems().get(getIndex());

                        // 创建自定义 Dialog 以查看作业描述
                        Dialog<ButtonType> dialog = new Dialog<>();
                        dialog.setTitle("查看作业");
                        dialog.setHeaderText("查看作业");

                        // 创建 TextArea 并设置为只读
                        TextArea textArea = new TextArea(homework.getHomeworkDescription());
                        textArea.setPrefSize(600, 400);
                        textArea.setEditable(false); // 设置 TextArea 为不可编辑

                        dialog.getDialogPane().setContent(textArea);

                        // 只添加关闭按钮
                        dialog.getDialogPane().getButtonTypes().addAll(ButtonType.CLOSE);

                        dialog.showAndWait();
                    });
                    setContentDisplay(ContentDisplay.RIGHT);
                }
            }
        });


        TableColumn<Homework, Date> homeworkEndDateCol = new TableColumn<>("截止日期");
        homeworkEndDateCol.setCellValueFactory(new PropertyValueFactory<>("homeworkEndDate"));
        homeworkEndDateCol.setPrefWidth(120);

        TableColumn<Homework, String> homeworkStatusCol = new TableColumn<>("作业状态");
        homeworkStatusCol.setCellValueFactory(new PropertyValueFactory<>("homeworkStatus"));
        homeworkStatusCol.setPrefWidth(100);

        TableColumn<Homework, Void> submissionColumn = new TableColumn<>("提交");
        submissionColumn.setPrefWidth(70);
        Callback<TableColumn<Homework, Void>, TableCell<Homework, Void>> detailsCellFactory = new Callback<>() {
            @Override
            public TableCell<Homework, Void> call(final TableColumn<Homework, Void> param) {
                final TableCell<Homework, Void> cell = new TableCell<>() {
                    private final Button submitButton = new Button("提交作业");

                    {
                        submitButton.setOnAction(event -> {
                            Homework homework = getTableView().getItems().get(getIndex());
                            System.out.println("Selected Homework name: " + homework.getHomeworkName());

                            // 创建提交作业的对话框
                            Dialog<ButtonType> dialog = new Dialog<>();
                            dialog.setTitle("提交作业");
                            dialog.setHeaderText("提交作业：" + homework.getHomeworkName());

                            TextArea submissionTextArea = new TextArea();
                            submissionTextArea.setPromptText("输入提交的内容...");
                            submissionTextArea.setPrefSize(400, 300);

                            dialog.getDialogPane().setContent(submissionTextArea);

                            ButtonType submitButtonType = new ButtonType("提交", ButtonBar.ButtonData.OK_DONE);
                            dialog.getDialogPane().getButtonTypes().addAll(submitButtonType, ButtonType.CANCEL);

                            dialog.showAndWait().ifPresent(response -> {
                                if (response == submitButtonType) {
                                    // 获取用户提交的内容
                                    String submissionContent = submissionTextArea.getText();

                                    // 创建并保存新的 Submission 对象
                                    Submission submission = new Submission();
                                    submission.setHomeworkId(homework.getHomeworkId());

                                    submission.setSubmittedBy(user.getUserId()); // 当前用户ID
                                    submission.setSubmissionContent(submissionContent);
                                    submission.setSubmissionCreationDate(new Date());

                                    try {
                                        submissionController.submitHomework(submission);
                                    } catch (SQLException e) {
                                        throw new RuntimeException(e);
                                    }
                                    SuccessView.success(primaryStage,"提交成功");

                                    // 刷新表格
                                    getTableView().refresh();
                                    homeworkTable.refresh();
                                }
                            });
                        });
                    }

                    @Override
                    protected void updateItem(Void item, boolean empty) {
                        super.updateItem(item, empty);
                        if (empty) {
                            setGraphic(null);
                        } else {
                            setGraphic(submitButton);
                        }
                    }
                };
                return cell;
            }
        };
        submissionColumn.setCellFactory(detailsCellFactory);

        // 将列添加到表格中
        homeworkTable.getColumns().addAll(homeworkIdCol, homeworkNameCol, descriptionColumn, homeworkEndDateCol, homeworkStatusCol,submissionColumn);

        // 从数据库查询属于当前用户的作业
        List<Homework> homeworkList = homeworkController.fetchHomeworksForStudent(user.getUserId());

        // 将数据添加到表格
        homeworkTable.getItems().addAll(homeworkList);

        // 设置表格的宽度和其他属性
        homeworkTable.setPrefWidth(600);
        homeworkTable.setPrefHeight(400);

        // 将表格添加到中心Box中
        centerBox.getChildren().add(homeworkTable);
    }

    private void setCenterContentForUser(Stage primaryStage, User user) throws SQLException {
        centerBox.getChildren().clear();
        centerBox.setPadding(new Insets(10, 10, 0, 0));

        TableView<User> tableView = new TableView<>();

        TableColumn<User, String> userIdColumn = new TableColumn<>("用户ID");
        userIdColumn.setCellValueFactory(data -> new SimpleStringProperty(String.valueOf(data.getValue().getUserId())));

        ObservableList<String> roleNameList = FXCollections.observableArrayList(roleController.getAllRoleNames());
        TableColumn<User, String> roleColumn = new TableColumn<>("角色");
        roleColumn.setCellValueFactory(data -> {
            int roleId = data.getValue().getRoleId();
            String roleName = roleController.getRoleNameByRoleId(roleId);
            return new SimpleStringProperty(roleName);
        });
        roleColumn.setCellFactory(ComboBoxTableCell.forTableColumn(roleNameList));
        roleColumn.setOnEditCommit(event -> {
            User editedUser = event.getRowValue();
            String newRoleName = event.getNewValue();
            int newRoleId = roleController.getRoleIdByRoleName(newRoleName);
            if (newRoleId != -1) {
                editedUser.setRoleId(newRoleId);
                userController.updateUserInDatabase(editedUser);
            }
        });

        TableColumn<User, String> userAccountColumn = new TableColumn<>("用户账号");
        userAccountColumn.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getUserAccount()));
        userAccountColumn.setCellFactory(TextFieldTableCell.forTableColumn());
        userAccountColumn.setOnEditCommit(event -> {
            User editedUser = event.getRowValue();
            editedUser.setUserAccount(event.getNewValue());
            userController.updateUserInDatabase(editedUser);
        });

        TableColumn<User, String> userNameColumn = new TableColumn<>("用户名");
        userNameColumn.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getUserName()));
        userNameColumn.setCellFactory(TextFieldTableCell.forTableColumn());
        userNameColumn.setOnEditCommit(event -> {
            User editedUser = event.getRowValue();
            editedUser.setUserName(event.getNewValue());
            userController.updateUserInDatabase(editedUser);
        });

        TableColumn<User, String> userEmailColumn = new TableColumn<>("用户邮箱");
        userEmailColumn.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getUserEmail()));
        userEmailColumn.setCellFactory(TextFieldTableCell.forTableColumn());
        userEmailColumn.setOnEditCommit(event -> {
            User editedUser = event.getRowValue();
            editedUser.setUserEmail(event.getNewValue());
            userController.updateUserInDatabase(editedUser);
        });

        TableColumn<User, String> userPhoneColumn = new TableColumn<>("用户电话");
        userPhoneColumn.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getUserPhone()));
        userPhoneColumn.setCellFactory(TextFieldTableCell.forTableColumn());
        userPhoneColumn.setOnEditCommit(event -> {
            User editedUser = event.getRowValue();
            editedUser.setUserPhone(event.getNewValue());
            userController.updateUserInDatabase(editedUser);
        });

        TableColumn<User, String> userStatusColumn = new TableColumn<>("用户状态");
        userStatusColumn.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getUserStatus().toString()));
        userStatusColumn.setCellFactory(ComboBoxTableCell.forTableColumn("ACTIVE", "SUSPENDED", "DELETED"));
        userStatusColumn.setOnEditCommit(event -> {
            User editedUser = event.getRowValue();
            String newStatusString = event.getNewValue();
            User.UserStatus newStatus = User.UserStatus.valueOf(newStatusString.toUpperCase());  // 确保字符串与枚举匹配
            editedUser.setUserStatus(newStatus);
            userController.updateUserInDatabase(editedUser);
        });

        tableView.getColumns().addAll(userIdColumn, roleColumn, userAccountColumn, userNameColumn, userEmailColumn, userPhoneColumn, userStatusColumn);

        tableView.setItems(userController.getAllUser());

        // 设置表格可编辑
        tableView.setEditable(true);

        // 限制表格高度，过多项时可以滚动
        tableView.setMaxHeight(800);
        tableView.setPrefHeight(Region.USE_COMPUTED_SIZE);

        // 将按钮和表格放在VBox中，并确保TableView支持滚动
        VBox tableContainer = new VBox(10);
        tableContainer.setPadding(new Insets(10));
        tableContainer.getChildren().add(tableView);

        // 添加ScrollPane来包裹VBox, 允许上下滚动
        ScrollPane scrollPane = new ScrollPane();
        scrollPane.setContent(tableContainer);
        scrollPane.setFitToWidth(true);
        scrollPane.setFitToHeight(true);

        centerBox.getChildren().addAll(scrollPane);
    }

    private void setCenterContentForPermission() {
        centerBox.getChildren().clear();
        centerBox.setPadding(new Insets(10, 10, 0, 0));

        // 初始化 GridPane 布局
        GridPane gridPane = new GridPane();
        gridPane.setHgap(30);
        gridPane.setVgap(30);

        // 定义角色名称和权限名称
        String[] roles = {"系统管理员", "教师", "学生"};
        String[] permissions = {"权限管理的权限", "管理用户的权限", "查看所有的作业、提交的权限", "布置作业的权限",
                "点评自己的作业的权限", "统计自己的作业分数的权限", "提交作业的权限"};

        // 为每个角色和权限创建标题
        for (int i = 0; i < roles.length; i++) {
            Label roleLabel = new Label(roles[i]);
            roleLabel.setStyle("-fx-font-size: 24px;-fx-font-family: 'Arial';");
            gridPane.add(roleLabel, i + 1, 0);  // 添加角色标题作为列头
        }
        for (int j = 0; j < permissions.length; j++) {
            Label permissionLabel = new Label(permissions[j]);
            permissionLabel.setStyle("-fx-font-size: 24px;-fx-font-family: 'Arial';");
            gridPane.add(permissionLabel, 0, j + 1);  // 添加权限标题作为行头
        }

        // 遍历角色和权限，创建复选框
        for (int permIndex = 0; permIndex < permissions.length; permIndex++) {
            for (int roleIndex = 0; roleIndex < roles.length; roleIndex++) {
                CheckBox checkBox = new CheckBox();
                checkBox.setStyle("-fx-pref-width: 40px; -fx-pref-height: 40px;");

                // 从数据库加载当前角色的权限状态
                boolean isChecked = permissionController.loadRolePermissionStatus(roleIndex + 1, permIndex + 1);
                checkBox.setSelected(isChecked);

                // 添加到 GridPane 中
                gridPane.add(checkBox, roleIndex + 1, permIndex + 1);

                // 设置复选框的监听事件
                int roleId = roleIndex + 1;
                int permissionId = permIndex + 1;
                checkBox.setOnAction(event -> {
                    boolean newStatus = checkBox.isSelected();
                    permissionController.updateRolePermission(roleId, permissionId, newStatus);  // 更新数据库
                });
            }
        }


        centerBox.getChildren().add(gridPane);
    }


    private void setCenterContentForHomework(Stage primaryStage, User user) throws SQLException {
        centerBox.getChildren().clear();
        centerBox.setPadding(new Insets(10, 0, 0, 0));

        List<Permission> permissions = null;
        try {
            permissions = permissionController.getUserPermissionsByRoleId(user.getRoleId());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        List<Permission> finalPermissions = permissions;

        HBox buttonBox = new HBox(100);
        buttonBox.setAlignment(Pos.CENTER);

        Button addHomeworkBtn = new Button("新增作业");
        Button queryHomeworkBtn = new Button("查询作业");
        addHomeworkBtn.setStyle("-fx-pref-width: 120px;-fx-pref-height: 40px;-fx-font-size: 16px;");
        queryHomeworkBtn.setStyle("-fx-pref-width: 120px;-fx-pref-height: 40px;-fx-font-size: 16px;");
        addHomeworkBtn.setOnAction(e -> addHomework(primaryStage, user, finalPermissions));
        queryHomeworkBtn.setOnAction(e -> queryHomework(primaryStage, user));

        TableView<Homework> homeworkTable = new TableView<>();
        homeworkTable.setEditable(true);
        homeworkTable.setStyle("-fx-pref-height: 600px;-fx-min-height: 400px;-fx-max-height: 800px;");

        TableColumn<Homework, Integer> peopleColumn = new TableColumn<>("教师ID");
        peopleColumn.setCellValueFactory(new PropertyValueFactory<>("createBy"));
        peopleColumn.setPrefWidth(50);

        TableColumn<Homework, String> idColumn = new TableColumn<>("作业ID");
        idColumn.setCellValueFactory(new PropertyValueFactory<>("homeworkId"));
        idColumn.setPrefWidth(50);

        TableColumn<Homework, String> nameColumn = new TableColumn<>("作业名称");
        nameColumn.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getHomeworkName()));
        nameColumn.setPrefWidth(150);
        nameColumn.setCellFactory(TextFieldTableCell.forTableColumn());
        nameColumn.setOnEditCommit(event -> {
            Homework editedHomework = event.getRowValue();

            // 检查权限，确保用户是该作业的创建者
            if (editedHomework.getCreateBy() != user.getUserId()) {
                AlartView.alart((Stage) nameColumn.getTableView().getScene().getWindow(), "您没有权限修改该作业！");
                nameColumn.getTableView().refresh();
                return;
            }

            // 用户有权限，执行更新
            editedHomework.setHomeworkName(event.getNewValue());
            try {
                homeworkController.updateHomeworkInDatabase(editedHomework);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        });

        TableColumn<Homework, String> descriptionColumn = new TableColumn<>("作业描述");
        descriptionColumn.setPrefWidth(150);

        descriptionColumn.setCellValueFactory(data -> {
            String fullDescription = data.getValue().getHomeworkDescription();
            int maxLength = 30; // 截取的最大字符数
            String shortenedDescription;

            // 如果内容超过 maxLength 个字符，截取并添加省略号
            if (fullDescription.length() > maxLength) {
                shortenedDescription = fullDescription.substring(0, maxLength) + "...";
            } else {
                shortenedDescription = fullDescription;
            }
            return new SimpleStringProperty(shortenedDescription);
        });

        descriptionColumn.setCellFactory(column -> new TableCell<Homework, String>() {
            private final Button editButton = new Button("编辑");

            @Override
            protected void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);
                if (empty || item == null) {
                    setText(null);
                    setGraphic(null);
                } else {
                    setText(item);
                    setGraphic(editButton);
                    editButton.setOnAction(event -> {
                        Homework homework = getTableView().getItems().get(getIndex());

                        // 检查用户权限
                        if (homework.getCreateBy() != user.getUserId()) {
                            AlartView.alart((Stage) getTableView().getScene().getWindow(), "您没有权限修改该作业描述！");
                            return;
                        }

                        // 创建自定义 Dialog 以编辑作业描述
                        Dialog<ButtonType> dialog = new Dialog<>();
                        dialog.setTitle("编辑作业描述");
                        dialog.setHeaderText("修改作业描述");
                        TextArea textArea = new TextArea(homework.getHomeworkDescription());
                        textArea.setWrapText(true);
                        textArea.setPrefSize(600, 400);
                        dialog.getDialogPane().setContent(textArea);

                        ButtonType okButtonType = new ButtonType("确定", ButtonBar.ButtonData.OK_DONE);
                        dialog.getDialogPane().getButtonTypes().addAll(okButtonType, ButtonType.CANCEL);

                        dialog.showAndWait().ifPresent(response -> {
                            if (response == okButtonType) {
                                String newDescription = textArea.getText();
                                homework.setHomeworkDescription(newDescription); // 保存完整的新描述
                                setText(newDescription.length() > 30 ? newDescription.substring(0, 30) + "..." : newDescription); // 更新表格中的显示
                                try {
                                    homeworkController.updateHomeworkInDatabase(homework);
                                } catch (SQLException e) {
                                    throw new RuntimeException(e);
                                }
                                getTableView().refresh();
                            }
                        });
                    });
                    setContentDisplay(ContentDisplay.RIGHT);
                }
            }
        });

        TableColumn<Homework, Date> deadlineColumn = new TableColumn<>("截止日期");
        deadlineColumn.setCellValueFactory(data -> new SimpleObjectProperty<>(data.getValue().getHomeworkEndDate()));
        deadlineColumn.setPrefWidth(120);
        deadlineColumn.setCellFactory(column -> new TableCell<Homework, Date>() {
            private final DatePicker datePicker = new DatePicker();
            @Override
            protected void updateItem(Date item, boolean empty) {
                super.updateItem(item, empty);
                if (empty) {
                    setText(null);
                    setGraphic(null);
                } else {
                    if (item != null) {
                        java.sql.Date sqlDate = (java.sql.Date) item;
                        LocalDate localDate = sqlDate.toLocalDate();
                        datePicker.setValue(localDate);
                    }
                    setGraphic(datePicker);
                    setContentDisplay(ContentDisplay.GRAPHIC_ONLY);

                    datePicker.focusedProperty().addListener((obs, wasFocused, isNowFocused) -> {
                        if (isNowFocused) {
                            Homework homework = getTableView().getItems().get(getIndex());
                            datePicker.setDisable(homework.getCreateBy() != user.getUserId());
                        }
                    });
                    datePicker.setOnAction(event -> {
                        LocalDate selectedDate = datePicker.getValue();
                        if (selectedDate != null) {
                            Homework homework = getTableView().getItems().get(getIndex());
                            java.sql.Date newDate = java.sql.Date.valueOf(selectedDate);
                            homework.setHomeworkEndDate(newDate);
                            try {
                                homeworkController.updateHomeworkInDatabase(homework);
                            } catch (SQLException e) {
                                throw new RuntimeException(e);
                            }
                            getTableView().refresh();
                        }
                    });
                }
            }
        });

        TableColumn<Homework, Date> submissionTimesColumn = new TableColumn<>("提交次数");
        submissionTimesColumn.setCellValueFactory(new PropertyValueFactory<>("submissionTimes"));
        submissionTimesColumn.setPrefWidth(60);

        TableColumn<Homework, Double> gradeColumn = new TableColumn<>("平均成绩");
        gradeColumn.setCellValueFactory(new PropertyValueFactory<>("homeworkGrade"));
        gradeColumn.setPrefWidth(60);

        TableColumn<Homework, Void> statsColumn = new TableColumn<>("成绩统计");
        statsColumn.setPrefWidth(60);
        Callback<TableColumn<Homework, Void>, TableCell<Homework, Void>> statsCellFactory = new Callback<>() {
            @Override
            public TableCell<Homework, Void> call(final TableColumn<Homework, Void> param) {
                final TableCell<Homework, Void> cell = new TableCell<>() {
                    private final Button statsButton = new Button("统计");
                    {
                        statsButton.setOnAction(event -> {
                            Homework homework = getTableView().getItems().get(getIndex());

                            // 权限检查
                            if (finalPermissions.stream().noneMatch(permission -> permission.getPermissionId() == 3)) {
                                if (homework.getCreateBy() != user.getUserId()) {
                                    AlartView.alart(primaryStage, "您没有权限查看作业！");
                                    return;
                                }
                            }
                            if (finalPermissions.stream().noneMatch(permission -> permission.getPermissionId() == 6)) {
                                AlartView.alart(primaryStage, "您没有权限查看作业！");
                                return;
                            }

                            // 创建新对话框
                            Stage statsStage = new Stage();
                            statsStage.setTitle("成绩统计");

                            // 设置X轴和Y轴
                            CategoryAxis xAxis = new CategoryAxis();
                            xAxis.setLabel("分数区间");
                            NumberAxis yAxis = new NumberAxis();
                            yAxis.setLabel("提交数量");

                            // 创建柱状图
                            BarChart<String, Number> barChart = new BarChart<>(xAxis, yAxis);
                            barChart.setTitle("作业提交成绩分布");

                            // 获取所有提交成绩
                            List<Submission> submissions = null; // 需要实现这个方法
                            try {
                                submissions = submissionController.selectSubmissionByHomeworkId(homework.getHomeworkId());
                            } catch (SQLException e) {
                                throw new RuntimeException(e);
                            }

                            // 初始化区间计数
                            int[] rangesCount = new int[5]; // 5个区间的计数
                            for (Submission submission : submissions) {
                                double grade = submission.getSubmissionGrade();
                                if (grade < 60) {
                                    rangesCount[0]++;
                                } else if (grade < 70) {
                                    rangesCount[1]++;
                                } else if (grade < 80) {
                                    rangesCount[2]++;
                                } else if (grade < 90) {
                                    rangesCount[3]++;
                                } else {
                                    rangesCount[4]++;
                                }
                            }

                            // 将成绩区间数据添加到柱状图中
                            XYChart.Series<String, Number> series = new XYChart.Series<>();
                            series.setName(homework.getHomeworkName());

                            series.getData().add(new XYChart.Data<>("0-60", rangesCount[0]));
                            series.getData().add(new XYChart.Data<>("60-70", rangesCount[1]));
                            series.getData().add(new XYChart.Data<>("70-80", rangesCount[2]));
                            series.getData().add(new XYChart.Data<>("80-90", rangesCount[3]));
                            series.getData().add(new XYChart.Data<>("90-100", rangesCount[4]));

                            // 将数据系列添加到柱状图
                            barChart.getData().add(series);

                            // 创建新的场景并添加柱状图
                            Scene scene = new Scene(barChart, 800, 600);
                            statsStage.setScene(scene);
                            statsStage.show();
                        });


                    }

                    @Override
                    protected void updateItem(Void item, boolean empty) {
                        super.updateItem(item, empty);
                        if (empty) {
                            setGraphic(null);
                        } else {
                            setGraphic(statsButton);
                        }
                    }
                };
                return cell;
            }
        };
        statsColumn.setCellFactory(statsCellFactory);

        TableColumn<Homework, Date> statuesColumn = new TableColumn<>("作业状态");
        statuesColumn.setCellValueFactory(new PropertyValueFactory<>("homeworkStatus"));
        statuesColumn.setPrefWidth(80);

        TableColumn<Homework, Void> deleteColumn = new TableColumn<>("操作");
        deleteColumn.setPrefWidth(50);
        Callback<TableColumn<Homework, Void>, TableCell<Homework, Void>> cellFactory = new Callback<>() {
            @Override
            public TableCell<Homework, Void> call(final TableColumn<Homework, Void> param) {
                final TableCell<Homework, Void> cell = new TableCell<>() {
                    private final Button deleteButton = new Button("删除");
                    {
                        deleteButton.setOnAction(event -> {
                            Homework homework = getTableView().getItems().get(getIndex());

                            if(homework.getCreateBy() != user.getUserId()){
                                AlartView.alart(primaryStage, "您没有权限删除该作业！");
                                return;
                            }
                            // 检查 HomeworkStatus 是否已经是 DELETED
                            if (homework.getHomeworkStatus() == Homework.HomeworkStatus.DELETED) {
                                return;
                            }
                            // 弹出警告对话框
                            Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
                            alert.setTitle("确认删除");
                            alert.setHeaderText("确认删除该作业？");
                            alert.setContentText("删除后无法恢复，确定继续吗？");

                            // 显示对话框并等待用户响应
                            alert.showAndWait().ifPresent(response -> {
                                if (response == ButtonType.OK) {
                                    homework.setHomeworkStatus(Homework.HomeworkStatus.DELETED);
                                    try {
                                        homeworkController.updateHomeworkInDatabase(homework);
                                    } catch (SQLException e) {
                                        throw new RuntimeException(e);
                                    }
                                    getTableView().refresh();
                                }
                            });
                        });
                    }
                    @Override
                    protected void updateItem(Void item, boolean empty) {
                        super.updateItem(item, empty);
                        if (empty) {
                            setGraphic(null);
                        } else {
                            setGraphic(deleteButton);
                        }
                    }
                };
                return cell;
            }
        };
        deleteColumn.setCellFactory(cellFactory);

        TableColumn<Homework, Void> detailsColumn = new TableColumn<>("提交详情");
        detailsColumn.setPrefWidth(80);
        Callback<TableColumn<Homework, Void>, TableCell<Homework, Void>> detailsCellFactory = new Callback<>() {
            @Override
            public TableCell<Homework, Void> call(final TableColumn<Homework, Void> param) {
                final TableCell<Homework, Void> cell = new TableCell<>() {
                    private final Button detailsButton = new Button("点评作业");
                    {
                        detailsButton.setOnAction(event -> {
                            Homework homework = getTableView().getItems().get(getIndex());

                            if(homework.getCreateBy() != user.getUserId()){
                                AlartView.alart(primaryStage, "您没有权限点评该作业！");
                                return;
                            }
                            if (finalPermissions.stream().noneMatch(permission -> permission.getPermissionId() == 5)) {
                                AlartView.alart(primaryStage, "您没有权限点评作业！");
                                return;
                            }

                            List<Submission> submissions = null;
                            try {
                                submissions = submissionController.selectSubmissionByHomeworkId(homework.getHomeworkId());
                                // 更新作业数据
                                homeworkController.updateHomeworkDataOnLogin();
                            } catch (SQLException e) {
                                throw new RuntimeException(e);
                            }
                            getTableView().refresh();
                            homeworkTable.refresh();

                            SubmissionDetailsView submissionDetailsView = new SubmissionDetailsView((Stage) getTableView().getScene().getWindow(), submissions);
                            submissionDetailsView.showAndWait();
                        });
                    }

                    @Override
                    protected void updateItem(Void item, boolean empty) {
                        super.updateItem(item, empty);
                        if (empty) {
                            setGraphic(null);
                        } else {
                            setGraphic(detailsButton);
                        }
                    }
                };
                return cell;
            }
        };
        detailsColumn.setCellFactory(detailsCellFactory);

        homeworkTable.getColumns().addAll(peopleColumn,idColumn,nameColumn,descriptionColumn,submissionTimesColumn,gradeColumn,statsColumn,deadlineColumn,statuesColumn,deleteColumn,detailsColumn);

        // 获取作业列表
        if (finalPermissions.stream().noneMatch(permission -> permission.getPermissionId() == 3)) {
            homeworkTable.getItems().addAll(homeworkController.tryGetHomeworkByUser(user,true));
        }else{
            homeworkTable.getItems().addAll(homeworkController.tryGetHomeworkByUser(user,false));
        }

        buttonBox.getChildren().addAll(addHomeworkBtn, queryHomeworkBtn);

        // 限制表格高度，过多项时可以滚动
        homeworkTable.setMaxHeight(300);
        homeworkTable.setPrefHeight(Region.USE_COMPUTED_SIZE);

        // 将按钮和表格放在VBox中，并确保TableView支持滚动
        VBox tableContainer = new VBox(10);
        tableContainer.setPadding(new Insets(10));
        tableContainer.getChildren().add(homeworkTable);

        // 添加ScrollPane来包裹VBox, 允许上下滚动
        ScrollPane scrollPane = new ScrollPane();
        scrollPane.setContent(tableContainer);
        scrollPane.setFitToWidth(true);
        scrollPane.setFitToHeight(true);

        centerBox.getChildren().addAll(buttonBox, scrollPane);
    }


    public void addHomework(Stage primaryStage, User user, List<Permission> finalPermissions) {
        if (finalPermissions.stream().noneMatch(permission -> permission.getPermissionId() == 4)) {
            AlartView.alart(primaryStage, "您没有权限布置作业！");
            return;
        }

        // 创建一个新的弹出窗口
        Stage dialog = new Stage();
        dialog.initModality(Modality.APPLICATION_MODAL);
        dialog.initOwner(primaryStage);
        dialog.setTitle("添加作业");

        // 创建输入字段
        TextField nameField = new TextField();
        TextArea descriptionField = new TextArea();
        DatePicker endDatePicker = new DatePicker();
        nameField.setPromptText("作业名称");
        descriptionField.setPromptText("作业描述");
        endDatePicker.setPromptText("选择结束日期");
        nameField.setPrefWidth(420);
        descriptionField.setPrefWidth(420);
        endDatePicker.setPrefWidth(420);
        descriptionField.setPrefHeight(420);

        Button saveButton = new Button("保存");
        Button cancelButton = new Button("取消");
        saveButton.setStyle("-fx-pref-width: 120px;-fx-pref-height: 40px;-fx-font-size: 20px;");
        cancelButton.setStyle("-fx-pref-width: 120px;-fx-pref-height: 40px;-fx-font-size: 20px;");

        Label nameLabel = new Label("作业名称:");
        Label descriptionLabel = new Label("作业描述:");
        Label endDateLabel = new Label("结束日期:");
        Label studentLabel = new Label("选择学生:");

        nameLabel.setStyle("-fx-font-size: 20px;-fx-font-weight: bold;");
        descriptionLabel.setStyle("-fx-font-size: 20px;-fx-font-weight: bold;");
        endDateLabel.setStyle("-fx-font-size: 20px;-fx-font-weight: bold;");
        studentLabel.setStyle("-fx-font-size: 20px;-fx-font-weight: bold;");

        // 获取学生列表
        List<User> students;
        try {
            students = userController.getUsersByRoleId(3);  // 获取roleId为3的学生列表
        } catch (SQLException ex) {
            AlartView.alart(primaryStage, "获取学生列表失败！");
            return;
        }

        VBox studentCheckBoxes = new VBox(10);
        List<CheckBox> studentCheckBoxList = new ArrayList<>();
        for (User student : students) {
            HBox studentRow = new HBox(10); // HBox 用于水平排列 Label 和 CheckBox，间距为 10

            // 创建一个 Label
            Label userLabel = new Label(student.getUserEmail() + "      "+ student.getUserPhone());
            userLabel.setPrefWidth(300); // 设置 Label 的宽度，方便对齐

            // 创建一个 CheckBox 来显示用户的名字
            CheckBox checkBox = new CheckBox(student.getUserName());

            // 将 Label 和 CheckBox 添加到 HBox 中
            studentRow.getChildren().addAll(checkBox, userLabel);

            // 将 HBox 添加到 VBox 中
            studentCheckBoxList.add(checkBox);
            studentCheckBoxes.getChildren().add(studentRow);
        }
        studentCheckBoxes.setPrefWidth(400);

        ScrollPane scrollPane = new ScrollPane(studentCheckBoxes);
        scrollPane.setPrefSize(420, 200);
        scrollPane.setFitToWidth(true);

        GridPane gridPane = new GridPane();
        gridPane.setHgap(10);
        gridPane.setVgap(10);
        gridPane.setAlignment(Pos.CENTER);
        gridPane.add(nameLabel, 0, 0);
        gridPane.add(nameField, 1, 0);
        gridPane.add(descriptionLabel, 0, 1);
        gridPane.add(descriptionField, 1, 1);
        gridPane.add(endDateLabel, 0, 2);
        gridPane.add(endDatePicker, 1, 2);
        gridPane.add(studentLabel, 0, 3);
        gridPane.add(scrollPane, 1, 3);
        gridPane.add(saveButton, 0, 4);
        gridPane.add(cancelButton, 1, 4);

        scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
        scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);

        saveButton.setOnAction(e -> {
            String homeworkName = nameField.getText();
            String homeworkDescription = descriptionField.getText();
            LocalDate localDate = endDatePicker.getValue();

            if (homeworkName.isEmpty()) {
                AlartView.alart(primaryStage, "作业名称不能为空！");
                return;
            }
            if (homeworkDescription.isEmpty()) {
                AlartView.alart(primaryStage, "作业描述不能为空！");
                return;
            }
            if (localDate == null) {
                AlartView.alart(primaryStage, "必须选择结束日期！");
                return;
            }
            LocalDate today = LocalDate.now(); // 获取今天的日期
            if (localDate.isBefore(today)) {
                AlartView.alart(primaryStage, "所选结束日期已过期！");
                return;
            }
            Date homeworkEndDate = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

            boolean hasSelectedStudent = studentCheckBoxList.stream().anyMatch(CheckBox::isSelected);
            if (!hasSelectedStudent) {
                AlartView.alart(primaryStage, "至少需要选择一个学生！");
                return;
            }

            // 如果数据有效，保存作业（这里可以调用保存方法）
            Homework newHomework = new Homework();
            newHomework.setHomeworkName(homeworkName);
            newHomework.setHomeworkDescription(homeworkDescription);
            newHomework.setHomeworkEndDate(homeworkEndDate);
            newHomework.setCreateBy(user.getUserId());

            try {
                // 保存作业
                homeworkController.addHomework(newHomework);

                // 获取刚刚插入的 HomeworkId (如果是自动生成的主键)
                int newHomeworkId = newHomework.getHomeworkId();  // 你需要确保此 ID 被正确设置

                // 确保 HomeworkId 已成功保存
                if (newHomeworkId == 0) {
                    throw new SQLException("作业ID未生成，无法保存学生记录。");
                }

                // 遍历选中的学生并保存到 HomeworkStudent 表
                for (int i = 0; i < students.size(); i++) {
                    if (studentCheckBoxList.get(i).isSelected()) {
                        HomeworkStudent homeworkStudent = new HomeworkStudent();
                        homeworkStudent.setHomeworkId(newHomeworkId);
                        homeworkStudent.setStudentId(students.get(i).getUserId());
                        homeworkStudent.setStatus(HomeworkStudent.Status.ASSIGNED);

                        homeworkController.addHomeworkStudent(homeworkStudent);  // 保存作业学生记录
                    }
                }
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }

            dialog.close();
        });


        // 取消按钮的事件处理
        cancelButton.setOnAction(e -> dialog.close());

        // 创建场景并展示对话框
        Scene scene = new Scene(gridPane, 600, 600);
        dialog.setScene(scene);
        dialog.show();
    }


    private void queryHomework(Stage primaryStage, User user) {
        //TODO 有空再做
    }

    private void setCenterContentForAccount(Stage primaryStage, User currentUser) {
        centerBox.getChildren().clear();
        centerBox.setPadding(new Insets(100, 0, 0, 0));

        HBox buttonBox = new HBox(100);
        buttonBox.setAlignment(Pos.CENTER);

        Button resetPasswordBtn = new Button("设置密码");
        Button exitBtn = new Button("退出登陆");

        resetPasswordBtn.setStyle("-fx-pref-width: 180px;-fx-pref-height: 60px;-fx-font-size: 24px;");
        exitBtn.setStyle("-fx-pref-width: 180px;-fx-pref-height: 60px;-fx-font-size: 24px;");
        buttonBox.getChildren().addAll(exitBtn, resetPasswordBtn);

        resetPasswordBtn.setOnAction(e -> tryResetPassword(primaryStage, currentUser));
        exitBtn.setOnAction(e -> exit(primaryStage));

        centerBox.getChildren().add(buttonBox);
    }

    private void tryResetPassword(Stage primaryStage, User currentUser) {
        // 创建新窗口的 Stage
        Stage resetPasswordStage = new Stage();
        resetPasswordStage.setTitle("重置密码");

        // 创建布局容器
        VBox layout = new VBox(10);
        layout.setPadding(new Insets(20));

        // 创建两个 Label 和两个 PasswordField
        Label newPasswordLabel = new Label("输入新密码:");
        PasswordField newPasswordField = new PasswordField();

        Label renewPasswordLabel = new Label("确认新密码:");
        PasswordField renewPasswordField = new PasswordField();

        // 创建确认按钮
        Button confirmBtn = new Button("确认");
        confirmBtn.setStyle("-fx-pref-width: 100px; -fx-pref-height: 30px;");

        // 设置按钮事件
        confirmBtn.setOnAction(e -> userController.tryResetPassword(newPasswordField.getText(), renewPasswordField.getText(), currentUser, resetPasswordStage));

        // 将控件添加到布局
        layout.getChildren().addAll(newPasswordLabel, newPasswordField, renewPasswordLabel, renewPasswordField, confirmBtn);
        layout.setAlignment(Pos.CENTER);

        // 创建新 Scene 并设置到新 Stage
        Scene scene = new Scene(layout, 300, 200);
        resetPasswordStage.setScene(scene);

        // 设置为模态窗口，阻止对其他窗口的操作
        resetPasswordStage.initModality(Modality.WINDOW_MODAL);
        resetPasswordStage.initOwner(primaryStage);

        // 显示新窗口
        resetPasswordStage.showAndWait();
    }

    private void exit(Stage primaryStage) {
        primaryStage.close();
        LoginView loginView = new LoginView();
        Stage loginStage = new Stage();
        loginView.start(loginStage);
    }

    private void setButtonStyle(Button button, String backgroundColor) {
        button.setStyle("-fx-pref-width: 200px;" +
                "-fx-pref-height: 80px;" +
                "-fx-font-size: 28px;" +
                "-fx-text-fill: rgb(0,0,0);" +
                "-fx-background-color: " + backgroundColor + ";" +
                "-fx-font-family: 'Arial';");
    }
}
